﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices.AccountManagement;

namespace VPNService
{
    internal class WindowsAccountHelper
    {
        private static PrincipalContext pc = new PrincipalContext(ContextType.Machine, Environment.MachineName);

        public static string AddUser(string userName, string[] groups, string password, DateTime? expireDate)
        {
            UserPrincipal user = new UserPrincipal(pc, userName, password, true)
            {
                AccountExpirationDate = expireDate,
                PasswordNeverExpires = true,
                Description = string.Join(",", groups)
            };
            user.Save();
            AddUserToGroup(user, groups);
            return user.Sid.ToString();
        }

        public static void AddUserToGroup(UserPrincipal user, string[] groups)
        {
            if (user == null) return;

            GroupPrincipal gp;
            foreach (string g in groups)
            {
                gp = GroupPrincipal.FindByIdentity(pc, g);
                if (gp != null)
                {
                    if (!gp.Members.Contains(user))
                    {
                        gp.Members.Add(user);
                    }
                }
                gp.Save();
            }
        }

        public static void AddUserToGroup(string userName, string[] groups)
        {
            UserPrincipal user = UserPrincipal.FindByIdentity(pc, userName);
            AddUserToGroup(user, groups);
        }


        public static void UpdateUser(string sid, string userName, string[] groups, string password, DateTime? expireDate, bool enable)
        {
            UserPrincipal u = GetUserInfoBySID(sid);
            if (u == null)
                return;

            u.Name = userName;
            u.AccountExpirationDate = expireDate;
            u.Description = string.Join(",", groups);
            u.Enabled = enable;
            u.Save();
            if (!string.IsNullOrEmpty(password))
                u.SetPassword(password);
            GroupPrincipal og = GroupPrincipal.FindByIdentity(pc, u.GetGroups().First(a => a.Name.ToLower().StartsWith("q")).Name);
            og.Members.Remove(u);
            og.Save();
            AddUserToGroup(u.Name, groups);
        }

        public static UserPrincipal GetUserInfoBySID(string sid)
        {
            return UserPrincipal.FindByIdentity(pc, IdentityType.Sid, sid);
        }

    }
}
